import { showModal } from "@/utils/toast";

/**
 * 申请权限
 * @param {String} permissionCode 权限标识
 * @param {String} permissionName 权限名称
 * @returns Promise
 */
export function applyPermission(permissionCode, permissionName) {
  return new Promise((resolve) => {
    uni.getSetting({
      success(res) {
        if (res.authSetting[permissionCode]) {
          resolve()
        } else {
          // 发起授权
          uni.authorize({
            scope: permissionCode,
            success() {
              resolve()
            },
            fail() {
              // 引导用户授权
              showModal({
                content: `请授权访问${permissionName}`,
                success(res) {
                  if (res.confirm) {
                    uni.openSetting();
                  }
                },
              });
            },
          });
        }
      },
    });
  })
}